/**
 * setOrderClass(type:number) //添加class, 根据type参数（1|2|3|4）判断字段类型并添加排序样式
 * orderList(type: number) // click 事件，根据type参数（1|2|3|4）判断字段类型然后排序，并通过flag1|flag2|flag3|flag4值通知setOrderClass
 * flag1 = true; flag2 = true; flag3 = true; flag4 = true; //为排序样式标识，true为升序icon，false为降序icon
 */
import {Component, OnInit, Output, EventEmitter} from '@angular/core';
import {AccountService} from "../service/account-service/account.service";
import {PaginationModel} from "../../../common-module/pagenation-component/pagination.model";
import * as _ from 'lodash';

@Component({
  selector: 'iotek-account-list',
  templateUrl: './account-list.component.html',
  styleUrls: ['./account-list.component.less'],
  providers: [AccountService]
})
export class AccountListComponent implements OnInit {
  flag1 = true;
  flag2 = true;
  flag3 = true;
  flag4 = true;
  public toastConfig = {};
  private listBack = [];
  //列表显示
  accounts = [];

  constructor(private accountService: AccountService) {
  }

  ngOnInit() {
    this.getAccounts(1); // initialize data
  }

  // 排序图标样式
  setOrderClass(type: number) {
    let flag;
    switch (type) {
      case 1:
        flag = this.flag1;
        break;
      case 2:
        flag = this.flag2;
        break;
      case 3:
        flag = this.flag3;
        break;
      case 4:
        flag = this.flag4;
        break;
    }
    let classes = {
      "glyphicon": true,
      "glyphicon-chevron-up": flag,
      "glyphicon-chevron-down": !flag
    };
    return classes;
  }

// 根据字段排序
  orderList(type: number) {
    if (type == 1) {
      this.flag1 = !this.flag1;
      this.sortby = "roleName";
      this.asc = this.flag1.toString();
    } else if (type == 2) {
      this.flag2 = !this.flag2;
      this.sortby = "username";
      this.asc = this.flag2.toString();
    } else if (type == 3) {
      this.flag3 = !this.flag3;
      this.sortby = "phoneNumber";
      this.asc = this.flag3.toString();
    } else if (type == 4) {
      this.flag4 = !this.flag4;
      this.sortby = "createTime";
      this.asc = this.flag4.toString();
    }
    this.getAccounts(1);
  }

//获取账户列表
  getAccounts(pn) {
    this.accountService.getItems(pn, this.pageSize, this.keywords, this.sortby, this.asc).then((res)=> {
      this.accounts = res.resultList;
      this.listBack = _.clone(res.resultList);
      this.pageTotal = res.totalPage;
      this.pager = new PaginationModel(this.pageTotal, pn, this.pageNoClickCallback, 'md');
    });
  }

//删除账号
  delete(account) {
    this.accountService.delete(account.id).then((res)=> {
      this.toastConfig = {
        title: res.title,
        type: res.status.toLowerCase(),
        content: res.content,
        random: Math.random()
      };
      this.getAccounts(1);
    });
  }

  //分页，查询 关键字
  pageSize = 10; //初始化分页大小为10
  pageTotal = 0;
  keywords = '';
  sortby = '';
  asc = 'true'; //初始化为升序
  // 关键字查询
  search() {
    this.getAccounts(1);
  }

// 分页大小选项列表
  pageSizeSelect = [10, 15,
    20, 25, 30];
//引入分页组件
  public pager: PaginationModel = new PaginationModel(this.pageTotal, 10, this.pageNoClickCallback, 'md');
//分页点击事件
  private pageNoClickCallback: (number) => void = (pn: number) => {
    this.getAccounts(pn);
  }
// 分页大小选项列表改变时重载数据
  reloadPage($event) {
    this.getAccounts(1);
  }

// input事件，自动获取焦点
  public onSearchInput($event) {
    this.accounts = _.filter(this.listBack, function (acc) {
      return acc.username && acc.username.lastIndexOf($event) > -1;
    })
  }

// onclose 自定义事件，关闭窗口
  close($event) {
    this.isClosed = $event.closed;
    this.toastConfig = $event.toastConfig;
    this.getAccounts(1); //刷新数据
  }

  /* click 事件
   ** 账户新增或编辑窗口
   ** flag==true新增账户，反之编辑账户
   */
  editAccountInfo;

  openpop(flag: boolean, account: any) {
    if (flag) {
      this.editAccountInfo = {'closed': false, 'edit': false, 'account': {}};
    } else {
      this.editAccountInfo = {
        'closed': false,
        'edit': true,
        'account': {
          'id': account.id,
          'roleId': account.roleId,
          'roleName': account.roleName,
          'name': account.username,
          'phone': account.phoneNumber,
          'remark': account.comment
        }
      };
    }
    this.setPopWindow(this.editAccountInfo);
  }

  /* 设置popover window
   * isEdit：用来判断是编辑还是新增
   * */
  isEdit = false;
  isClosed = true;
  rolesList: any;
  title = "";
  account = "";

  setPopWindow(info) {
    this.getRoleList();
    this.isClosed = info.closed;
    this.isEdit = info.edit;
    if (this.isEdit) {
      this.title = "修改账户";
    } else {
      this.title = "添加新账号";
    }
    this.account = info.account;
  }

  //获取用户角色
  getRoleList() {
    this.accountService.getRoles().then((res)=> {
      this.rolesList = res;
    })
  }

}
